﻿using CocoaAni.Net.WebSockets.Server.Attributes;
using CocoaAni.Net.WebSockets.Server.Controllers;
using CocoaAni.Net.WebSockets.Server.Exceptions;
using System.Reflection;

namespace CocoaAni.Net.WebSockets.Server.DefineInfos;

public class ControllerInfo
{
    public ControllerInfo(Type type)
    {
        Instance = (WebSocketController)Activator.CreateInstance(type)!;
        CollectHandlers(type);
    }

    public ControllerInfo(WebSocketController controller)
    {
        Instance = controller;
        CollectHandlers(controller.GetType());
    }

    public string MapPath => Instance.MapPath;
    public WebSocketController Instance { get; set; }
    public Dictionary<string, HandlerDefineInfo> HandlerInfos { get; internal set; } = null!;

    private void CollectHandlers(Type type)
    {
        var methodInfos = type.GetMethods();
        HandlerInfos = methodInfos.Select(t => (t, t.GetCustomAttribute<MessageHandlerAttribute>()))
            .Where(t => t.Item2 != null)
            .Select(t => new HandlerDefineInfo(t.t, t.Item2)).ToDictionary(t => t.Name);
        if (!HandlerInfos.ContainsKey(MessageHandlerAttribute.Default))
        {
            throw new WebSocketControllerException($"Default Handler Not Found On=>{GetType().FullName} ", Instance);
        }
    }
}